package DBLayer;
import ModelLayer.*;

import java.sql.*;


public class DBModtagVare implements IFDBModtagVare {
	private Connection con;
	
	public DBModtagVare() {
		con = DBConnection.getInstance().getDBcon();
	}
	
	public ModtagVare findModtagVare(int modtagOrdreID, int produktID, boolean retriveAssociation)
    {   String wClause = "  modtagOrdreID = '" + modtagOrdreID + "'" + " and produktID = '" + produktID + "'";
        return singleWhere(wClause, retriveAssociation);
    }
	
	public ModtagVare findModtagOrdreID(int modtagOrdreID, boolean retriveAssociation)
    {   String wClause = "  modtagOrdreID = '" + modtagOrdreID + "'";
        return singleWhere(wClause, retriveAssociation);
    }
	
	public ModtagVare findProduktID(int produktID, boolean retriveAssociation)
    {   String wClause = "  produktID = '" + produktID + "'";
        return singleWhere(wClause, retriveAssociation);
    }
	
	private ModtagVare singleWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		ModtagVare mvObj = new ModtagVare();
                
	        String query =  buildQuery(wClause);
                System.out.println(query);
		try{ // read the employee from the database
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
	 		if( results.next() ){
                            mvObj = buildModtagVare(results);
                            //assocaition is to be build
                            stmt.close();
                            
			}
                        else{ //no employee was found
                            mvObj = null;
                        }
		}//end try	
	 	catch(Exception e){
	 		System.out.println("Query exception: "+e);
	 	}
		return mvObj;
	}
	
	private String buildQuery(String wClause)
	{
	    String query="SELECT modtagordreid, antal, produktid  FROM ModtagVare";
		
		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;
			
		return query;
	}
	
	private ModtagVare buildModtagVare(ResultSet results)
    {   ModtagVare mvObj = new ModtagVare();
        try{ // the columns from the table emplayee  are used
        	mvObj.setModtagOrdre(new Ordre(null, 0, null, results.getInt("modtagordreid"), null, null, null));
        	mvObj.setAntal(results.getInt("antal"));
        	mvObj.setProdukt(new Produkt(0, results.getInt("produktid"), 0, null, null, null));
            }
       catch(Exception e)
       {
           System.out.println("error in building the employee object");
       }
       return mvObj;
    }
	
}